import requests
import bs4
import os
import re
import sys
import time

urlStatus = 'http://poj.org/status'
listStatus = [
	'Run ID', 'User', 'Problem', 'Result',
	'Memory', 'Time', 'Language', 'Code Length',
	'Submit Time' ]
dictError = { 
	0:u'get page error', -1:u'Waiting', 
	-2:u'Compiling', -3:u'Running & Judging' }


	
def get_results(session, statusData):
	try:
		response = session.get(urlStatus, params=statusData)
		page = response.content
	except:
		return 0, None
	
	try:
		bs = bs4.BeautifulSoup(page)
		table = bs.html.body.find('table', cellspacing='0')
		tr = table.find('tr', align='center')
		results = list(tr.strings)
		for key in dictError:
			if dictError[key] == results[3]:
				return key, None
		else: return 1, results
	except:
	  	return 0, None

def deal_with_results(results):
	if results[3] != "Accepted":
		results.insert(4, "-")
		results.insert(4, "-")
	return results

def get_status(user_id):
	session = requests.session()
	statusData = { 'user_id':user_id }
	for ith in range(5):
		res, results = get_results(session, statusData)
		#print results
		if res <= 0: 
			time.sleep(1)
		else:
			results = deal_with_results(results)	
			parse_result = "%d|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s" \
			% (0, "Success", results[0], results[8], results[1], \
			results[2], results[3], results[6], results[5], \
			results[4],results[7])
			return parse_result
	
	parse_result = "%d|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s" \
	%  (1, "Parse Error", "-", "-", "-", "-", "-", "-", "-", "-", "-")	
	return parse_result

if __name__ == '__main__':
	print get_status("gvj0")
